const dayjs = require('dayjs')
const { Router } = require('express')
const multer = require('multer')
const db = require('../utils/db')
const fs = require('fs')

const storage = multer.diskStorage({
  //保存路径
  destination: 'public/uploadFiles/', // 保存的路径
  //保存在 destination 中的文件名
  filename: function (req, file, cb) {
    // cb(null, file.originalname + '-' + Date.now())
    // 处理中文乱码
    cb(null, Buffer.from(file.originalname, 'latin1').toString('utf-8'))
  }
})

const upload = multer({ storage })

const router = new Router()

router.use(function (req, res, next) {
  // console.log('执行时间戳：' + Date.now())
  next()
})

// 上传文件
router.post('/upload', upload.single('file'), (req, res) => {
  const { mimetype, filename, size } = req.file
  const filepath = '/images/uploadFiles/' + filename
  const updateTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  const sql = `insert into t_files (filename, mimetype, size, filepath, update_time) values ($1, $2, $3, $4, $5)`
  const values = [filename, mimetype, size, filepath, updateTime]

  db.query({ text: sql, values }, err => {
    if (err) {
      console.log('err: ', err.message)
    } else {
      res.send({
        code: 200,
        message: '上传成功',
        data: {
          mimetype,
          filename,
          size,
          filepath: 'http://' + req.headers.host + filepath,
          updateTime
        }
      })
    }
  })
})

// 查询文件列表
router.get('/list', (req, res) => {
  const { filename, pageNum = 1, pageSize = 10 } = req.query
  let queryFileListSql = `select id, filename, mimetype, size, filepath, to_char(update_time, 'YYYY-MM-dd HH24:mi:ss') "updateTime" from t_files order by id limit $1 offset $2`
  let queryFileListValues = [pageSize, pageSize * (pageNum - 1)]

  let queryCountSql = `select count(*) from t_files`
  let queryCountValues = []
  if (filename) {
    queryFileListSql = `select id, filename, mimetype, size, filepath, to_char(update_time, 'YYYY-MM-dd HH24:mi:ss') "updateTime" from t_files where filename like '%'||$1||'%' order by id limit $2 offset $3`
    queryFileListValues = [filename, ...queryFileListValues]
    queryCountSql = `select count(*) from t_files where filename like '%'||$1||'%'`
    queryCountValues = [filename]
  }

  db.query(
    { text: queryCountSql, values: queryCountValues },
    (err, queryCountResult) => {
      if (err) {
        console.log('query count error: ' + err)
      } else {
        const total = Number(queryCountResult.rows[0].count)
        db.query({ text: queryFileListSql, values: queryFileListValues }, (err, result) => {
          for (const item of result.rows) {
            item.filepath = 'http://' + req.headers.host + item.filepath
          }
          if (err) {
            console.log('query file list error: ', err.message)
          } else {
            res.send({
              code: 200,
              message: '获取文件列表成功',
              data: result.rows,
              total
            })
          }
        })
      }
    },
    res
  )
})

// 删除文件（单个/批量）
router.delete('/delete/:ids', (req, res) => {
  const { ids } = req.params
  const sql = `delete from t_files where id in (${ids}) returning filename`
  db.query(sql, (err, result) => {
    for (const item of result.rows) {
      item.filepath = 'http://' + req.headers.host + item.filepath
    }
    if (err) {
      console.log('err: ', err.message)
    } else {
      if (result.rowCount) {
        // 删除服务器中的文件
        // process.cwd() 用于获取进程执行文件夹地址
        // fs.unlink(process.cwd() + `/public/uploadFiles/${result.rows[0].filename}`, err => {
        //   if (err) {
        //     throw err
        //   } else {
        //     console.log('文件删除成功')
        //   }
        // })
      }
      res.send({
        code: 200,
        message: result.rowCount ? '删除成功' : '删除失败！原因：删除项不存在'
      })
    }
  })
})

// 根据文件 ID 下载文件（暂时用不到）
// router.get('/download', (req, res) => {
//   const { id } = req.query

//   const sql = `select * from t_files where id = $1`
//   const values = [id]
//   db.query({ text: sql, values }, (err, result) => {
//     if (err) {
//       console.log('err: ', err.message)
//     } else {
//       const filepath = process.cwd() + result.rows[0].filepath.replace('/images', '/public')
//       //格式必须为 binary，否则会出错
//       // 创建文件可读流
//       const crs = fs.createReadStream(filepath)
//       crs.on('data', chunk => {
//         res.write(chunk)
//       })
//       crs.on('end', () => {
//         res.status(200)
//         res.end()
//       })
//     }
//   })
// })

module.exports = router
